import React from 'react';
import {Table, Card} from 'antd';
import routes from './routes';
import {Link} from 'react-router-dom';
import PropTypes from 'prop-types';
import {conventEnumValueToString, formatDateTime, exportDownload} from '../utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {PERMISSION} from './constants';
import {hasPermissions, generateRowSpanDatas} from './utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {exports} from './api';
import {vehicleFollowListDestinationPort} from '../Enum';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH, DATETIME_FORMAT, DATE_FORMAT} from '../constants';

const basePath = fetch.basePath || '';
const url = '/#/dcs/sales/vehicleFollowList';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    onClickExport = r => {
        this.setState({
            loading: true
        });
        const data = this.props.data.find(v => v.id === r);
        exports({invoiceCode: data.invoiceCode,
            saleConfirmationrCode: data.saleConfirmationrCode}).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
        this.props.onChangeSort();
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    render() {
        const {pageIndex, pageSize, total} = this.props;
        const {brands} = this.props.initEnumData;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.invoiceCode',
                defaultMessage: '发票号'
            }),
            dataIndex: 'invoiceCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'invoiceCode' && this.props.sortedOrder,
            render: (text, record) => ({
                children: `${record.saleConfirmationrCode}/${record.invoiceCode}`,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.invoiceDate',
                defaultMessage: '开票日期'
            }),
            dataIndex: 'invoiceDate',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'invoiceDate' && this.props.sortedOrder,
            render: (text, record) => ({
                children: formatDateTime(text, DATE_FORMAT),
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.containerCode',
                defaultMessage: '箱号'
            }),
            dataIndex: 'containerCode',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.containerDate',
                defaultMessage: '装箱日期'
            }),
            dataIndex: 'containerDate',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'containerDate' && this.props.sortedOrder,
            render: (text, record) => ({
                children: formatDateTime(text, DATE_FORMAT),
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.leadMark',
                defaultMessage: '铅封号'
            }),
            dataIndex: 'leadMark',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.frameCode',
                defaultMessage: '铁架子编号'
            }),
            dataIndex: 'frameCode',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.emptyContainerWeight',
                defaultMessage: '空箱重量(KG)'
            }),
            dataIndex: 'emptyContainerWeight',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.threeVINWeight',
                defaultMessage: '三车重量(KG)'
            }),
            dataIndex: 'threeVINWeight',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.totalWeight',
                defaultMessage: '总重量(KG)'
            }),
            dataIndex: 'totalWeight',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.bindingBands',
                defaultMessage: '绑扎带'
            }),
            dataIndex: 'bindingBands',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.carriageWeight',
                defaultMessage: '车架子毛重(KG)'
            }),
            dataIndex: 'carriageWeight',
            render: (text, record) => ({
                children: text,
                props: {
                    rowSpan: text ? record.rowSpan : 0,
                },
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.container',
                defaultMessage: '物料号'
            }),
            dataIndex: 'container',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.cheryCar',
                defaultMessage: 'CHERY CAR'
            }),
            dataIndex: 'cheryCar',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.version',
                defaultMessage: '车型'
            }),
            dataIndex: 'version',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.color',
                defaultMessage: '颜色'
            }),
            dataIndex: 'color',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.perGW',
                defaultMessage: '单车重量(KG)'
            }),
            dataIndex: 'perGW',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.glonassNO',
                defaultMessage: 'Glonass NO.'
            }),
            dataIndex: 'glonassNO',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.engineNumber',
                defaultMessage: '发动机号'
            }),
            dataIndex: 'engineNumber',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.displacement',
                defaultMessage: '排量'
            }),
            dataIndex: 'displacement',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.hsCode',
                defaultMessage: 'HS CODE'
            }),
            dataIndex: 'hsCode',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.vin',
                defaultMessage: 'VIN'
            }),
            dataIndex: 'vin',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.productionYear',
                defaultMessage: '产品年份'
            }),
            dataIndex: 'productionYear',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.ottc',
                defaultMessage: 'OTTC'
            }),
            dataIndex: 'ottc',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.qty',
                defaultMessage: '数量'
            }),
            dataIndex: 'qty',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.unitPriceExw',
                defaultMessage: '货值'
            }),
            dataIndex: 'unitPriceExw',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.insurance',
                defaultMessage: '保险费'
            }),
            dataIndex: 'insurance',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.freight1',
                defaultMessage: '运费一'
            }),
            dataIndex: 'freight1',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.freight2',
                defaultMessage: '运费二'
            }),
            dataIndex: 'freight2',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.totalAmount',
                defaultMessage: '总价格'
            }),
            dataIndex: 'totalAmount',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.vehicleDescribe',
                defaultMessage: '整车描述'
            }),
            dataIndex: 'vehicleDescribe',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.mileage',
                defaultMessage: '公里数(Km)'
            }),
            dataIndex: 'mileage',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.manufactureDate',
                defaultMessage: '生产日期'
            }),
            dataIndex: 'manufactureDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.from',
                defaultMessage: '起运港'
            }),
            dataIndex: 'from',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.to',
                defaultMessage: '目的港'
            }),
            dataIndex: 'to'
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.deliveryTerms',
                defaultMessage: '贸易条款'
            }),
            dataIndex: 'deliveryTerms',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.consignee',
                defaultMessage: '整车发票和铁架子发票的收货人'
            }),
            dataIndex: 'consignee',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.buyer',
                defaultMessage: '铁架子发票的买方'
            }),
            dataIndex: 'buyer',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.frameTradeTerms',
                defaultMessage: '铁架子贸易条款'
            }),
            dataIndex: 'frameTradeTerms',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.vehicleContractNo',
                defaultMessage: '整车合同号'
            }),
            dataIndex: 'vehicleContractNo',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.vehicleContractDate',
                defaultMessage: '整车合同日期'
            }),
            dataIndex: 'vehicleContractDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.frameContractNo',
                defaultMessage: '铁架子合同号'
            }),
            dataIndex: 'frameContractNo',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.contractDate',
                defaultMessage: '铁架子合同日期'
            }),
            dataIndex: 'contractDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.payment',
                defaultMessage: '付款方式'
            }),
            dataIndex: 'payment',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operaterTime',
                defaultMessage: '导入时间'
            }),
            dataIndex: 'operaterTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operaterName',
                defaultMessage: '导入人员'
            }),
            dataIndex: 'operaterName',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.isPrint',
                defaultMessage: '打印状态'
            }),
            dataIndex: 'isPrint',
            render: text => text === true ? this.props.intl.formatMessage({
                id: 'tablePanel.column.yes',
                defaultMessage: '是'
            }) : this.props.intl.formatMessage({
                id: 'tablePanel.column.no',
                defaultMessage: '否'
            })
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'options',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.update,
                        children: (
                            <a key="update" href={`${basePath}${url}/${r.vehicleFollowId}/update?saleConfirmationrCode=${r.saleConfirmationrCode}&invoiceCode=${r.invoiceCode}`}
                                data-id={r.id}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </a>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                    },
                    {
                        id: PERMISSION.export,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="export"
                                placement="topLeft"
                                onConfirm={r => this.onClickExport(r)}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={this.props.intl.formatMessage({
                                    id: 'tablePanel.message.export',
                                    defaultMessage: '是否导出？'
                                })}>
                                <a>{this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.export',
                                    defaultMessage: '导出'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.export) && hasPermissions(r.options, PERMISSION.export))
                    },
                ];
                return {
                    children: <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />,
                    props: {
                        rowSpan: t ? r.rowSpan : 0,
                    },
                };//<DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        if(brands.length > 1)
            columns.splice(0, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.brandCode',
                        defaultMessage: '品牌'
                    }),
                    dataIndex: 'brandCode',
                    render: (text, record) => ({
                        children: text,
                        props: {
                            rowSpan: text ? record.rowSpan : 0,
                        },
                    })
                });
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    initEnumData: getinitEnumData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


